package com.netty.demo.fundamental.uptime;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @author shengtao
 * @Description:
 * @date 2018/09/06 12:10
 */
public final class UptimeClinet {

    public static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));
    static final String HOST = "127.0.0.1";
    static final int PORT = 5001;
    static final int RECONNECT_DELAY = 10;
    private static final int READ_TIMEOUT = 10;

    private static final UptimeClinetHandler handler = new UptimeClinetHandler();
    private static final Bootstrap bs = new Bootstrap();
    public static void main(String[] args) throws Exception {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {

            bs.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(HOST,PORT)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new IdleStateHandler(READ_TIMEOUT, 0, 0),handler);
                        }
                    });
            //start
            bs.connect();
            Thread.sleep(Integer.MAX_VALUE);
        }finally {
            workerGroup.shutdownGracefully();
        }
    }
    static void connect() {
        bs.connect().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if(channelFuture.cause() != null){
                    handler.startTime = -1;
                    handler.println("Failed to connect: " + channelFuture.cause());
                }
            }
        });
    }

}
